import React, { useEffect } from 'react';
import { Modal, message } from "antd";
import DocumentSearch from "../components/document/DocumentSearch";
import DocumentToolbar from "../components/document/DocumentToolbar";
import DocumentList from "../components/document/DocumentList";
import DocumentModal from "../components/document/DocumentModal";
import PreviewModal from "../components/document/PreviewModal";
import TablePagination from '../../../components/TablePagination';
import * as documentService from '../services/documentService';
import { useGlobalShare } from '../../../models/globalShare';
import useDocumentState from '../models/documentState';

const DocumentPage = (props) => {

    const { themeColor } = useGlobalShare();
    const {
        documentLoading, setDocumentLoading,
        currentPage, setCurrentPage,
        pageSize, setPageSize,
        documentTotal, setDocumentTotal,
        documentList, setDocumentList,
        selectedRowKeys, setSelectedRowKeys,
        selectedRows, setSelectedRows,
        searchParams, setSearchParams,
        documentType, setDocumentType,
        documentModalVisible, setDocumentModalVisible,
        uploadedDocumentFile, setUploadedDocumentFile,
        onPreview, documentRecord, previewModalVisible, setPreviewModalVisible,
        onDownload, onDeleteDocument
    } = useDocumentState();

    useEffect(() => {
        documentService.getDocumentList({ current_page: "0", page_size: 10 }).then(res => {
            if (res.code == 200) {
                const data = res.data;
                setDocumentTotal(data.total);
                setDocumentList(data.records);
            }
        });
    }, []);

    const documentSearchProps = {
        themeColor,
        onSearch: (searchParams) => {
            searchParams.current_page = currentPage + "";
            searchParams.page_size = pageSize;
            setSearchParams(searchParams);
            documentService.getDocumentList({ ...searchParams }).then(res => {
                if (res.code == 200) {
                    const data = res.data;
                    setDocumentTotal(data.total);
                    setDocumentList(data.records);
                }
            });
        },
        onReset: () => {
            setSearchParams(null);
        },
    };

    const documentToolbarProps = {
        themeColor,
        onAddDocument: () => {
            setDocumentModalVisible(true);
        },
        beforeUpload: (file) => {
            const fileNames = file.name.split(".");
            const fileType = fileNames[fileNames.length - 1];
            if (["pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "txt"].indexOf(fileType) < 0) {
                message.error('只能上传pdf, doc, xls, ppt, txt格式的文档！');
                return false;
            }
            if (file.size / 1024 / 1024 / 1024 > 1) {
                message.error('上传大小限制为1G的文档！');
                return false;
            }

            console.log("DocumentPage uploadDocument file name => ", file.name);
            documentService.uploadDocument({ file });
            return true;
        },
        addSave: () => {},
        batchDelete: () => {
            if (selectedRowKeys.length == 0) {
                message.error("请选择要删除的记录！");
                return;
            }
            Modal.confirm({
                title: "删除",
                content: "确定删除选中的记录？",
                onOk() {
                    onDeleteDocument(selectedRowKeys);
                },
                onCancel() {}
            });
        },
        onExport: () => {}
    };

    const documentListProps = {
        currentPage,
        pageSize,
        documentList,
        documentLoading,
        onPreview,
        onDownload,
        rowSelection: {
            selectedRowKeys,
            selectedRows,
            onChange: (keys, selectedRows) => {
                setSelectedRowKeys(keys);
                setSelectedRows(selectedRows);
            },
        }
    };

    const tablePaginationProps = {
        total: documentTotal,
        currentPage,
        pageSize,
        onPageChange: (currentPage, pageSize) => {
            documentService.getDocumentList({ current_page: currentPage + "", page_size: pageSize, ...searchParams }).then(res => {
                if (res.code == 200) {
                    const data = res.data;
                    setDocumentTotal(data.total);
                    setDocumentList(data.records);
                }
            });
        },
        onShowSizeChange: (currentPage, pageSize) => {
            documentService.getDocumentList({ current_page: currentPage + "", page_size: pageSize, ...searchParams }).then(res => {
                if (res.code == 200) {
                    const data = res.data;
                    setDocumentTotal(data.total);
                    setDocumentList(data.records);
                }
            });
        },
    };

    const documentModalProps = {
        themeColor,
        documentModalVisible,
        documentType,
        documentLoading,
        changeDocumentType: (event) => {
            setDocumentType(event.target.value);
        },
        addDocument: () => {
            if (documentType == "Document") {
                setDocumentLoading(true);
                documentService.uploadDocument({ file: uploadedDocumentFile }).then(res => {
                    if (res.code == 200) {
                        setDocumentModalVisible(false);
                        setDocumentLoading(false);
                        documentService.getDocumentList({ current_page: currentPage + "", page_size: pageSize, ...searchParams }).then(res => {
                            if (res.code == 200) {
                                const data = res.data;
                                setDocumentTotal(data.total);
                                setDocumentList(data.records);
                            }
                        });
                    }
                });
            } else {
                setDocumentLoading(true);
                const inputDom = document.getElementById("documentModalWebsite");
                documentService.addDocumentWebsite({ website: inputDom.value }).then(res => {
                    if (res.code == 200) {
                        setDocumentModalVisible(false);
                        setDocumentLoading(false);
                        documentService.getDocumentList({ current_page: currentPage + "", page_size: pageSize, ...searchParams }).then(res => {
                            if (res.code == 200) {
                                const data = res.data;
                                setDocumentTotal(data.total);
                                setDocumentList(data.records);
                            }
                        });
                    }
                });
            }
        },
        closeDocumentModal: () => {
            setDocumentModalVisible(false);
        },
        beforeUpload: (file) => {
            const fileNames = file.name.split(".");
            const fileType = fileNames[fileNames.length - 1];
            if (["pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "txt"].indexOf(fileType) < 0) {
                message.error('只能上传pdf, doc, xls, ppt, txt格式的文档！');
                return false;
            }
            if (file.size / 1024 / 1024 / 1024 > 1) {
                message.error('上传大小限制为1G的文档！');
                return false;
            }

            console.log("DocumentPage uploadDocument file name => ", file.name);
            setUploadedDocumentFile(file);
            return true;
        }
    };

    const previewModalProps = {
        previewModalVisible,
        documentRecord,
        closePreviewModal: () => {
            setPreviewModalVisible(false);
        }
    }

    return (
        <div style={{ width: "calc(100% - 40px)", height: "calc(100% - 40px)", background: "#ffffff", padding: 20 }}>
            <DocumentSearch {...documentSearchProps} />
            <DocumentToolbar {...documentToolbarProps} />
            <DocumentList {...documentListProps} />
            <TablePagination {...tablePaginationProps} />

            <DocumentModal {...documentModalProps} />
            <PreviewModal { ...previewModalProps } />
        </div>
    );
}

export default DocumentPage;
